<template>
  <div class="course-manager">
    <!-- 操作栏 -->
    <div class="action-header">
      <div class="left-actions">
        <el-button type="primary" size="small" class="new-btn" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增
        </el-button>
        <el-button 
          type="danger" 
          size="small" 
          class="batch-delete-btn" 
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-tag type="info" class="filter-tag">Java</el-tag>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="请输入课程名称"
          class="search-input"
          size="small"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" @click="handleSearch">
          搜索
        </el-button>
      </div>
    </div>

    <!-- 课程表格 -->
    <el-table 
      :data="courseList" 
      border 
      style="width: 100%"
      class="compact-table"
      :header-cell-style="{background:'#FAFAFA', color:'#333'}"
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column prop="courseUuid" label="序号" width="60" align="center" />
      <el-table-column label="封面" width="100">
        <template #default="{row}">
          <el-image 
            :src="row.coverImage" 
            class="course-cover" 
            fit="cover"
            alt="封面">
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="courseName" label="课程名称" width="150" />
      <el-table-column prop="courseTeacher" label="授课老师" width="100" />
      <el-table-column prop="courseDescription" label="课程简介" min-width="280">
        <template #default="{row}">
          <div class="description-text">
            {{ row.courseDescription }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="120">
        <template #default="{row}">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{row}">
          <el-link type="primary" @click="handleEdit(row)">编辑</el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" @click="handleDelete(row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 课程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑课程' : '新增课程'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="courseForm"
        :rules="rules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="授课老师" prop="courseTeacher">
          <el-input v-model="courseForm.courseTeacher" placeholder="请输入授课老师" />
        </el-form-item>
        <el-form-item label="课时" prop="courseDuration">
          <el-input-number v-model="courseForm.courseDuration" :min="1" :max="200" />
        </el-form-item>
        <el-form-item label="课程封面" prop="coverImage" required>
          <el-upload
            class="cover-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <el-image 
              v-if="courseForm.coverImage" 
              :src="courseForm.coverImage" 
              class="uploaded-cover"
              fit="cover">
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传图片</div>
            </div>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x500px，支持jpg、png格式，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="课程简介" prop="courseDescription">
          <el-input
            v-model="courseForm.courseDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, Plus, Delete, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import type { FormInstance } from 'element-plus'
import { CourseEntity } from '../model/EduEntity'

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')

// 表格选择
const selectedRows = ref<CourseEntity[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 表单数据
const courseForm = ref<CourseEntity>(new CourseEntity())

// 表单验证规则
const rules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  courseTeacher: [
    { required: true, message: '请输入授课老师', trigger: 'blur' }
  ],
  courseDuration: [
    { required: true, message: '请输入课时', trigger: 'blur' }
  ],
  courseDescription: [
    { required: true, message: '请输入课程简介', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 课程列表数据
const courseList = ref<CourseEntity[]>([])

// 初始化加载数据
onMounted(() => {
  fetchCourseList()
})

// 格式化日期
const formatDate = (dateStr: string | Date) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    const params = {
      name: searchQuery.value,
      page: (currentPage.value - 1) * pageSize.value,
      rp: pageSize.value,
      sortname: '',
      sortorder: 'desc',
      isActive: 1
    }
    
    // 获取课程列表
    const response = await axios.post('/api/course/queryCourseListByPage', params, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('课程列表响应:', response.data)
    
    if (response.data && response.data.success) {
      courseList.value = response.data.data.map((item: any) => {
        return {
          courseUuid: item.id || item.courseUuid,
          courseName: item.name || item.courseName,
          coverImage: item.cover || item.coverImage,
          courseTeacher: item.user || item.courseTeacher,
          courseDuration: item.class_hour || item.courseDuration,
          courseDescription: item.introduction || item.courseDescription,
          createTime: item.create_time || item.createTime,
          remarks: item.remarks
        }
      })
    } else {
      ElMessage.error(response.data?.msg || '获取课程列表失败')
    }
    
    // 获取总数
    const totalResponse = await axios.post('/api/course/queryCourseListTotal', params, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('总数响应:', totalResponse.data)
    
    if (totalResponse.data && totalResponse.data.success) {
      total.value = totalResponse.data.data
    } else {
      ElMessage.error(totalResponse.data?.msg || '获取总数失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    
    courseList.value = [
      {
        courseUuid: '1',
        courseName: 'Java 从入门到精通',
        coverImage: 'kecheng1.jpg',
        courseTeacher: '张老师',
        courseDuration: 48,
        courseDescription: '《Java从入门到精通（第6版）》从初学者角度出发，通过通俗易懂的语言、丰富多彩的实例，详细讲解了使用Java语言进行程序开发需要掌握的知识。',
        createTime: '2022-02-21 15:01:39',
        remarks: ''
      },
      {
        courseUuid: '2',
        courseName: 'Spring Boot 编程思想',
        coverImage: 'kecheng2.jpg',
        courseTeacher: '李老师',
        courseDuration: 64,
        courseDescription: '《Spring Boot 编程思想（核心篇）》是《Spring Boot 编程思想》的核心篇，开篇总览Spring Boot核心特性，接着讨论自动装配（Auto-Configuration）与SpringApplication。',
        createTime: '2022-02-21 15:02:51',
        remarks: ''
      }
    ]
    total.value = courseList.value.length
    ElMessage.warning('使用本地模拟数据')
  } finally {
    loading.value = false
  }
}

// 表格选择变化
const handleSelectionChange = (rows: CourseEntity[]) => {
  selectedRows.value = rows
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchCourseList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchCourseList()
}

// 新增课程
const handleAdd = () => {
  isEdit.value = false
  courseForm.value = new CourseEntity()
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = (row: CourseEntity) => {
  isEdit.value = true
  courseForm.value = { ...row }
  dialogVisible.value = true
}

// 删除课程
const handleDelete = async (row: CourseEntity) => {
  try {
    await ElMessageBox.confirm('确认删除该课程吗？', '提示', {
      type: 'warning'
    })
    
    const response = await axios.post('/api/course/deleteCourse', [row.courseUuid], {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (response.data && response.data.success) {
      ElMessage.success('删除成功')
      fetchCourseList()
    } else {
      ElMessage.error(response.data?.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) return
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个课程吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.courseUuid)
    const response = await axios.post('/api/course/deleteCourse', ids, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (response.data && response.data.success) {
      ElMessage.success('批量删除成功')
      fetchCourseList()
    } else {
      ElMessage.error(response.data?.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 上传前校验
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理上传
const handleUpload = async (options: any) => {
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', options.file)
    
    // 发送上传请求
    const response = await axios.post('/api/upload/image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    if (response.data && response.data.success) {
      courseForm.value.coverImage = response.data.data
      ElMessage.success('上传成功')
    } else {
      const reader = new FileReader()
      reader.readAsDataURL(options.file)
      reader.onload = (e) => {
        if (e.target && e.target.result) {
          courseForm.value.coverImage = e.target.result as string
          ElMessage.success('本地预览成功')
        }
      }
    }
  } catch (error) {
    console.error('上传失败:', error)
    const reader = new FileReader()
    reader.readAsDataURL(options.file)
    reader.onload = (e) => {
      if (e.target && e.target.result) {
        courseForm.value.coverImage = e.target.result as string
        ElMessage.success('本地预览成功')
      }
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const submitData = {
      id: courseForm.value.courseUuid,
      name: courseForm.value.courseName,
      cover: courseForm.value.coverImage,
      user: courseForm.value.courseTeacher,
      class_hour: courseForm.value.courseDuration,
      introduction: courseForm.value.courseDescription
    }
    
    if (isEdit.value) {
      const response = await axios.post('/api/course/updateCourse', submitData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      if (response.data && response.data.success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchCourseList()
      } else {
        ElMessage.error(response.data?.msg || '更新失败')
      }
    } else {
      const response = await axios.post('/api/course/addCourse', submitData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      if (response.data && response.data.success) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        fetchCourseList()
      } else {
        ElMessage.error(response.data?.msg || '创建失败')
      }
    }
  } catch (error) {
    console.error(isEdit.value ? '更新失败:' : '创建失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.course-manager {
  padding: 16px;
  background: #fff;
}

.action-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-tag {
  margin-left: 12px;
}

.search-area {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.compact-table {
  margin-bottom: 16px;
}

.compact-table :deep(.el-table__cell) {
  padding: 8px 0;
  font-size: 13px;
}

.course-cover {
  width: 80px;
  height: 50px;
  border-radius: 3px;
  object-fit: cover;
}

.description-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 160px;
  height: 100px;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 80px;
  text-align: center;
}

.uploaded-cover {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 修改预览图片的样式 */
:deep(.el-image-viewer__wrapper) :deep(.el-image-viewer__img) {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 调整图片查看器的关闭按钮位置 */
:deep(.el-image-viewer__close) {
  color: #fff;
  opacity: 0.8;
  font-size: 30px;
  top: 30px;
  right: 30px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>